package rss;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.sun.syndication.feed.synd.SyndCategoryImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RSSReader {

	String url = "http://www.ebookshare.net/feed";
	ArrayList<String> URLlist;

	RSSReader(String _URL) {
		url = _URL;
		URLlist = new ArrayList<String>();
		URLListbuilder();
	}
	
	public ArrayList<String> getURLList() {
		return URLlist;
	}

	private void URLListbuilder() {
		try {
			URL feedUrl = new URL(url);
			SyndFeedInput input = new SyndFeedInput();
			SyndFeed syndFeed = input.build(new XmlReader(feedUrl));

			List<SyndEntry> entries = syndFeed.getEntries();
			SyndEntry entry = null;

			/* Subscription Info */
			for (int i = 0, j = entries.size(); i < j; i++) {
				entry = entries.get(i);
				URLlist.add(entry.getUri());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// @SuppressWarnings("unchecked")
	public void Output() throws Exception {

		URL feedUrl = new URL(url);
		SyndFeedInput input = new SyndFeedInput();
		SyndFeed syndFeed = input.build(new XmlReader(feedUrl));

		/* RSS */
		System.out.println("### getFeedType 	[" + syndFeed.getFeedType() + "]");
		System.out.println("### getLanguage 	[" + syndFeed.getLanguage() + "]");
		System.out.println("### getTitle 		[" + syndFeed.getTitle() + "]");
		System.out.println("### getPublishedDate 	[" + syndFeed.getPublishedDate() + "]");

		List<SyndEntry> entries = syndFeed.getEntries();
		SyndEntry entry = null;

		/* Subscription Info */
		for (int i = 0, j = entries.size(); i < j; i++) {
			entry = entries.get(i);
			System.out.println("### getTitle 		[" + entry.getTitle() + "]");
			System.out.println("### getUri 			[" + entry.getUri() + "]");
			System.out.println("### getDescription 	[" + entry.getDescription().getValue() + "]");
			System.out.println("### getPublishedDate[" + entry.getPublishedDate().getTime() + "]");

			/* Categories */
			StringBuffer cate = new StringBuffer();
			if (entry.getCategories() != null && entry.getCategories().size() > 0) {
				for (int ii = 0, jj = entry.getCategories().size(); ii < jj; ii++) {
					SyndCategoryImpl ss = (SyndCategoryImpl) entry.getCategories().get(ii);
					// cate.append(CommonUtils.replace(ss.getName(), " ", "")
					// ).append(",");
					cate.append(ss.getName());
				}
			}
			System.out.println("### category		[" + cate.toString() + "]");
		}
	}
}
